package com.qty.apkviewer.utils

import android.Manifest
import android.app.AppOpsManager
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.provider.Settings
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity

/**
 * 权限处理类
 */
object PermissionUtils {

    private const val TAG = "PermissionUtils"
    // 在 Android R (Android 11) 版本后用于申请管理外部存储的权限
    private const val MANAGE_EXTERNAL_STORAGE_PERMISSION = "android:manage_external_storage"
    // Android R (Androi 11） 版本前要申请的权限
    private val ANDROID_R_BEFORE_PERMISSIONS = listOf(
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE
    )
    // Android R (Android 11) 版本后要申请的权限
    @RequiresApi(Build.VERSION_CODES.R)
    private val ANDROID_R_LATER_PERMISSIONS = listOf(
        Manifest.permission.QUERY_ALL_PACKAGES
    )

    /**
     * 检查应用所有权限是否都已经获取
     *
     * @param context AppCompatActivity 对象
     * @return 所有权限已获取返回 true，否则返回 false
     */
    fun checkAllPermissions(context: AppCompatActivity): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            checkAndroidRAfterStoragePermission(context) && checkQueryAllPackagePermission(context)
        } else {
            checkAndroidRBeforeStoragePermission(context)
        }
    }

    /**
     * 检查应用是否获取了读写存储的权限
     *
     * @param context AppCompatActivity 对象
     * @return 所有权限已获取返回 true，否则返回 false
     */
    fun checkStoragePermission(context: AppCompatActivity): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            checkAndroidRAfterStoragePermission(context)
        } else {
            checkAndroidRBeforeStoragePermission(context)
        }
    }

    /**
     * 检查应用是否获取了查询安装包的权限
     *
     * @param context AppCompatActivity 对象
     * @return 所有权限已获取返回 true，否则返回 false
     */
    @RequiresApi(Build.VERSION_CODES.R)
    fun checkQueryAllPackagePermission(context: AppCompatActivity): Boolean {
        return context.checkSelfPermission(Manifest.permission.QUERY_ALL_PACKAGES) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 检查应用是否获取了 Android R 版本前的读写权限
     *
     * @param context AppCompatActivity 对象
     * @return 所有权限已获取返回 true，否则返回 false
     */
    private fun checkAndroidRBeforeStoragePermission(context: AppCompatActivity): Boolean {
        return (context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
                && (context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
    }

    /**
     * 检查应用是否获取了 Android R 版本后的读写权限
     *
     * @param context AppCompatActivity 对象
     * @return 所有权限已获取返回 true，否则返回 false
     */
    @RequiresApi(Build.VERSION_CODES.R)
    private fun checkAndroidRAfterStoragePermission(context: AppCompatActivity): Boolean {
        val appOps = context.getSystemService(AppOpsManager::class.java)
        val mode = appOps.unsafeCheckOpNoThrow(
            MANAGE_EXTERNAL_STORAGE_PERMISSION,
            context.applicationInfo.uid,
            context.packageName
        )
        return mode == AppOpsManager.MODE_ALLOWED
    }

    /**
     * 请求应用需要的所有权限
     *
     * @param context AppCompatActivity 对象
     * @param callback 请求完成后的回调
     */
    fun requstAllPermissions(context: AppCompatActivity, callback: RequestPermissionCallback?) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            requestQueryAllPackagesPermission(context) { result ->
                requestAndroidRAfterStoragePermission(context) {
                    if (result && it) {
                        callback?.onResult(true)
                    } else {
                        callback?.onResult(false)
                    }
                }
            }
        } else {
            requestAndroidRBeforeStoragePermission(context, callback)
        }
    }

    fun requestStoragePermisson(context: AppCompatActivity, callback: RequestPermissionCallback?) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            requestAndroidRAfterStoragePermission(context, callback)
        } else {
            requestAndroidRBeforeStoragePermission(context, callback)
        }
    }

    /**
     * 检查 {@link Manifest.permission.QUERY_ALL_PACKAGES} 权限是否获取
     *
     * @param context AppCompatActivity 对象
     * @return 如果 {@link Manifest.permission.QUERY_ALL_PACKAGES} 权限已获取返回 true，否则返回 false
     */
    @RequiresApi(Build.VERSION_CODES.R)
    fun requestQueryAllPackagesPermission(context: AppCompatActivity, callback: RequestPermissionCallback?) {
        val launcher = context.registerForActivityResult(ActivityResultContracts.RequestPermission()) {
            result -> callback?.onResult(result)
        }
        launcher.launch(Manifest.permission.QUERY_ALL_PACKAGES)
    }

    /**
     * 检查 Android R 版本前读写存储权限是否获取
     *
     * @param context AppCompatActivity 对象
     * @return 如果 {@link Manifest.permission.WRITE_EXTERNAL_STORAGE}、{@link Manifest.permission.READ_EXTERNAL_STORAGE} 权限已获取返回 true，否则返回 false
     */
    fun requestAndroidRBeforeStoragePermission(context: AppCompatActivity, callback: RequestPermissionCallback?) {
        val storagePermissions = listOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
        )
        val launcher = context.registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
            callback?.onResult(checkAndroidRBeforeStoragePermission(context))
        }
        launcher.launch(storagePermissions.toTypedArray())
    }

    /**
     * 检查 Android R 版本后读写存储权限是否获取
     *
     * @param context AppCompatActivity 对象
     * @return 如果权限已获取返回 true，否则返回 false
     */
    @RequiresApi(Build.VERSION_CODES.R)
    fun requestAndroidRAfterStoragePermission(context: AppCompatActivity, callback: RequestPermissionCallback?) {
        val launcher = context.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            callback?.onResult(checkAndroidRAfterStoragePermission(context))
        }
        val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
        launcher.launch(intent)
    }

    /**
     * 请求权限回调
     */
    fun interface RequestPermissionCallback {
        /**
         * 请求权限完成回调方法
         *
         * @param graint 请求权限结果，获取全部权限返回 true，否则返回 false
         */
        fun onResult(graint: Boolean)
    }
}